package testJdk.base.juc_test.test_lock;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : learn_jdk.base.juc_test.test_lock.WaitAndNotify
 * @Description : 类描述
 * Created by cyd on 2021-10-25 09:03:09
 */
public class ABCTest {
    public static void main(String[] args) {
        ABCTask task = new ABCTask();
        new Thread(task, "A").start();
        new Thread(task, "B").start();
        new Thread(task, "C").start();
    }
}

class ABCTask implements Runnable {

    private final Lock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();

    @SneakyThrows
    @Override
    public void run() {
        Thread currentThread = Thread.currentThread();
        String name = currentThread.getName();
        for (int i = 0; i < 30; i++) {
            try {
                lock.lockInterruptibly();
                if (name.equals("A")) {
                    System.out.println("A print");
                    // 一定要先唤醒，再等待，先等待了就没执行唤醒
                    conditionB.signal();
                    conditionA.await();
                }
                if (name.equals("B")) {
                    System.out.println("B print");
                    conditionC.signal();
                    conditionB.await();
                }
                if (name.equals("C")) {
                    System.out.println("C print");
                    conditionA.signal();
                    conditionC.await();
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
